<template>
	<view class="container-fixed">
		<!-- 状态栏 -->
		<view :class="statusBarViewClass"></view>
		<!-- 导航栏 -->
		<view class="customer-nav-view">
			<view class="customer-nav-left">
				<uni-icons type="back" color='#000000' size="24" @click="goBackPage"></uni-icons>
			</view>
			<view class="customer-nav-title">
				{{playerInfo.title}}
			</view>
			<view class="customer-nav-right">
				<uni-icons type="videocam-filled" color='#FF4F80' size="26" @click="searchDevice"></uni-icons>
			</view>
		</view>
		<!-- 播放器 -->
		<view class="player-container">
			<video id="myVideo" class="video-client" :title="playerInfo.title" controls autoplay enable-play-gesture
				show-mute-btn @timeupdate="changProgress" :src="playerInfo.src">
			</video>
		</view>
		<!-- 广告提醒 -->
		<!-- <view class="player-adf-tip">
			<uni-notice-bar style="padding: 5px 0 3px; margin: 0;" :text="ad_tip" background-color="#FFFFFF"
				color="#ff0000" scrollable :speed="30" showClose />
		</view> -->
		<!-- tabs 页 -->
		<view class="tab-view">
			<uni-segmented-control :current="currentTabs" :values="tabs" style-type="text" @clickItem="clickTabsItem"
				active-color="#FF4F80" inActiveColor="#000000" />
		</view>
		<!-- tabs 选项页 -->
		<view class="tabs-content">
			<view v-show="currentTabs === 0">
				<view class="player-mov-desc">
					<view class="video-desc-title">
						<text class="video-desc-title-text">{{playerInfo.title}}</text>
						<uni-icons class="favorite-icon" @click="setFavorite" size="32"
							:type="pageDate.isFavoriteMovie?'star-filled':'star'"
							:color="pageDate.isFavoriteMovie?'#FF4F80':'#555555'">
						</uni-icons>
					</view>
					<view class="video-opt-view">
						<view class="player-opt-item">
							<uni-icons type="fire-filled" color='#FF4F80' size="20"></uni-icons>
							<text>{{movieInfo?movieInfo.clickNum:'0'}}</text>
						</view>
						<view class="player-opt-item" @click="setUpNum()">
							<uni-icons type="hand-up-filled" color='#FF4F80' size="20"></uni-icons>
							<text>{{movieInfo?movieInfo.upNum:'0'}}</text>
						</view>
						<view class="player-opt-item" @click="setBadNum">
							<uni-icons type="hand-down-filled" color='#FF4F80' size="20"></uni-icons>
							<text>{{movieInfo?movieInfo.badNum:'0'}}</text>
						</view>
					</view>
					<view class="video-desc-item">
						<text>地区：{{movieInfo.country}}</text>
						<text>上映时间：{{movieInfo.releaseTime}}</text>
					</view>
					<view class="video-desc-item">
						<text>导演：{{movieInfo.director != null && movieInfo.director.length > 0 ? movieInfo.director : '未知'}}</text>
						<text v-if="movieInfo.actor != null && movieInfo.actor.length > 0">
							演员：{{movieInfo.actor}}
						</text>
						<text v-else>
							演员：
							<text v-for="actor,index in movieInfo.actresses" :key="index">
								{{(index == 0 ? '' : '、') + actor.name}}
							</text>
						</text>
					</view>
					<view class="video-desc-item">
						<text v-html="'简介：'+movieInfo.desc"></text>
					</view>
				</view>
			</view>
			<view v-show="currentTabs === 1">
				<view class="player-jj-view"
					v-if="pageDate && pageDate.movieInfoVoList && pageDate.movieInfoVoList.length > 0 ">
					<view v-for="item,index in pageDate.movieInfoVoList" :key="index"
						@click="goMovDetailPage(item.movieId, index+1)"
						:class="['player-jj-item', index+1 == pageDate.currentNum?'jj-selected':'']">
						{{ item.name }}
					</view>
				</view>
			</view>
			<view v-show="currentTabs === 2">
				<view class="player-comment-view" v-if="comment_list && comment_list.length > 0 ">
					<view class="player-comment-item" v-for="item,index in comment_list" :key="index">
						<image class="comment-user-img" mode="aspectFill"
							:src="item.userImg?(item.userImg.startsWith('http')?item.userImg:(api.host+item.userImg)):'/static/image/head_pic.png'">
						</image>
						<view class="comment-right">
							<view class="comment-user-name">{{item.nickName}}</view>
							<view class="comment-content">{{item.content}}</view>
							<view class="comment-time">{{item.createTime}}</view>
						</view>
					</view>
				</view>
				<!-- 输入区域 -->
				<view class="input-area">
					<textarea class="input-area-input" :class="{ 'appendRightButton': showSendButton }"
						v-model="comment_value" placeholder="看完想说点什么吗" :maxlength="-1" auto-height
						@input="inputHandle" />
					<button v-if="showSendButton" class="input-area-send-btn"
						:class="{ 'showSendButton': showSendButton }" @click="submitComment">↑</button>
				</view>
			</view>
		</view>

		<!-- 悬浮按钮 -->
		<zjw-float-button :label="btn_text" :initX="280" :initY="450" fontSize="30rpx" width="100rpx" bgColor="#FF4F80"
			@click="setPlaybackRate">
		</zjw-float-button>

		<!-- 通用选择器 -->
		<zjw-list-popup :title="selectDialog_title" ref="selectDialog" :data="selectDialog_data"
			@click="confirmSelected" optText="搜索设备" @clickOpt="searchDevice">
		</zjw-list-popup>
	</view>
</template>

<script setup>
	import {
		onUnmounted,
		onMounted,
		ref,
		nextTick,
		getCurrentInstance
	} from 'vue'
	import {
		onPageScroll,
		onLoad,
		onHide,
		onShow
	} from '@dcloudio/uni-app'
	import {
		showToast,
		getUserId,
		getUserInfo,
		getUserToken
	} from '@/utils/utils'
	import api from '@/config/api'
	import request from '@/utils/request'

	let dlna = uni.requireNativePlugin('JX-Dlna')
	const deviceList = ref([]) // 设备列表

	const videoContext = ref(null)

	const logo_img = ref("/static/image/logo.png")
	const ad_tip = ref("警告：视频资源采集于网络，视频内嵌广告为视频提供方制作，与本站无关！请勿相信视频内的广告！请勿相信视频内的广告！")

	const maxTop = ref(0)
	const statusBarViewClass = ref("status-bar-view-1")

	const tabs = ref(['简介', '剧集', '评论'])
	const currentTabs = ref(0)

	const playerInfo = ref({
		src: '',
		title: ""
	})
	const pageDate = ref({})
	const movieInfo = ref({})
	const comment_list = ref([])
	const videoParam = ref({
		token: getUserToken(),
		movieId: 0,
		num: 0
	})

	const showSendButton = ref(false) // 是否显示发送按钮
	const comment_value = ref(null)

	const btn_text = ref('x1') // 倍数文字
	const btn_index = ref(2) // 倍率下标
	const btn_rate = [0.5, 0.8, 1.0, 1.25, 1.5]

	const selectDialog = ref(null) // 选择器弹窗
	const selectDialog_title = ref('') // 选择器弹窗标题
	const selectDialog_data = ref([]) // 选择器弹窗数据

	// #ifndef H5
	// 保持屏幕常亮
	uni.setKeepScreenOn({
		keepScreenOn: true
	});
	// #endif

	onLoad((e) => {
		videoParam.value.movieId = e.movieId
		videoParam.value.num = e.num
		getVideoDetail()
	})

	onShow(() => {
		const instance = getCurrentInstance();
		videoContext.value = uni.createVideoContext('myVideo', instance);
	})

	onUnmounted(() => {
		dlna.removeAllEventListeners()
		dlna = null; // 手动将引用置为 null
	})

	// 搜索附近投屏设备
	const searchDevice = () => {
		showToast('正在搜索......')
		deviceList.value = []
		dlna.search(result => {
			if (result.type === 'add') {
				deviceList.value.push({
					'value': result.id,
					'label': result.name
				})
			} else {
				deviceList.value = deviceList.value.filter(x => x.value != result.id)
			}
		})
		// 打开通用选择器
		selectDialog_title.value = '可投屏设备列表'
		selectDialog_data.value = deviceList.value
		selectDialog.value.open()
	}

	// 通用选择器：确认选择
	const confirmSelected = (item) => {
		uni.showLoading({
			title: '正在投屏',
			mask: true,
		})
		dlnaPlay(item.value, playerInfo.value.src, playerInfo.value.title)
	}

	// 投屏播放
	const dlnaPlay = (id, url, title) => {
		dlna.play({
			'id': id,
			'url': url,
			'title': title
		}, result => {
			uni.hideLoading()
			showToast(result.msg)
		})
	}

	// 设置播放速度
	const setPlaybackRate = () => {
		let index = btn_index.value + 1
		if (index > 4) {
			btn_index.value = 0
		} else {
			btn_index.value = index
		}
		btn_text.value = 'x' + btn_rate[btn_index.value]
		videoContext.value.playbackRate(btn_rate[btn_index.value])
	}

	// 监听播放进度，上传观看进度
	let uploaded = false
	const changProgress = (e) => {
		if (!pageDate.value.isFavoriteMovie) {
			return
		}
		if (uploaded) {
			return
		}
		if (e.detail.currentTime > 0 && e.detail.duration > 9 &&
			e.detail.currentTime * 2 > e.detail.duration) {
			uploaded = true
			request.post(api.host + api.uploadProgressUrl, {
				token: getUserToken(),
				movieId: movieInfo.value.movieId,
				progress: pageDate.value.currentNum
			})
		}
	}

	// 获取影视详情
	const getVideoDetail = () => {
		request.get(api.host + api.videoDetailUrl, videoParam.value)
			.then(result => {
				pageDate.value = result.data
				movieInfo.value = result.data.movieInfo
				comment_list.value = result.data.movieInfo.comments
				if (movieInfo.value.path.startsWith('http')) {
					playerInfo.value.src = movieInfo.value.path
				} else {
					playerInfo.value.src = api.host + encodeURI(movieInfo.value.path).replace(/%5C/g, '/')
				}
				if (movieInfo.value.movieName == movieInfo.value.name) {
					playerInfo.value.title = movieInfo.value.movieName
				} else {
					playerInfo.value.title = movieInfo.value.movieName +
						" " + movieInfo.value.name
				}
			}).catch(() => {
				goBackPage()
			})
	}

	// 切换 tabs
	const clickTabsItem = (e) => {
		// 从0开始的
		currentTabs.value = e.currentIndex
		if (e.currentIndex == 2) {
			getCommentsByMovieId()
		}
	}

	// 获取评论
	const getCommentsByMovieId = () => {
		request.get(api.host + api.commentListUrl, {
			movieId: movieInfo.value.movieId
		}).then(result => {
			if (result.success) {
				comment_list.value = result.data
			}
		})
	}

	// 有内容输入时，显示发送按钮
	const inputHandle = () => {
		showSendButton.value = comment_value.value.length > 0
	}

	// 发表评论
	const submitComment = () => {
		request.post(api.host + api.submitCommentUrl, {
			token: getUserToken(),
			movieId: movieInfo.value.movieId,
			content: comment_value.value
		}).then(result => {
			if (result.success) {
				comment_value.value = ""
				getCommentsByMovieId()
				showToast(result.msg)
			}
		})
	}

	// 点赞
	const setUpNum = () => {
		request.post(api.host + api.setRecommendUrl, {
			movieId: movieInfo.value.movieId
		}).then(result => {
			if (result.success) {
				movieInfo.value.upNum = movieInfo.value.upNum + 1
			}
		})
	}

	// 差评
	const setBadNum = () => {
		request.post(api.host + api.setBadUrl, {
			movieId: movieInfo.value.movieId
		}).then(result => {
			if (result.success) {
				movieInfo.value.badNum = movieInfo.value.badNum + 1
			}
		})
	}

	// 收藏/取消
	const setFavorite = () => {
		request.post(api.host + api.setFavoriteUrl, {
			movieId: movieInfo.value.movieId,
			token: getUserToken()
		}).then(result => {
			if (result.success) {
				pageDate.value.isFavoriteMovie = !pageDate.value.isFavoriteMovie
			}
		})
	}

	// 前往详情页面
	const goMovDetailPage = (movieId, num) => {
		uni.redirectTo({
			url: '/pages/mov_detail/mov_detail?movieId=' + movieId + '&num=' + num,
		})
	}

	// 返回
	const goBackPage = () => {
		uni.navigateBack()
	}
</script>

<style lang="scss">
	@import url("mov_detail.css");
</style>